package pit.com.ordermobilesystem;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;

import pit.com.ordermobilesystem.http.HttpApiException;
import pit.com.ordermobilesystem.http.OrderSystemHttpService;
import pit.com.ordermobilesystem.http.Response;
import pit.com.ordermobilesystem.model.Item;
import pit.com.ordermobilesystem.model.Order;
import pit.com.ordermobilesystem.model.OrderItem;
import pit.com.ordermobilesystem.util.OrderConstant;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

// su ly luu vao database va dua len web la ok 
public class PaymentFragment extends Fragment implements OrderConstant {

	private EditText ed_Nametable;
	private EditText ed_NameCustomer;
	private EditText ed_Description;

	private ImageView imv_trove;
	private ImageView imv_hotline;
	private ImageView imv_lamlai;
	private ImageView imv_guidi;

	private Calendar cal;
	private String strDate;
	private Order order;
	private Item item;

	public Item getItem() {
		return item;
	}

	public void setItem(Item itemnew) {
		item = itemnew;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View rootView = inflater.inflate(R.layout.payment, container, false);

		ed_Nametable = (EditText) rootView.findViewById(R.id.ed_Nametable);
		ed_NameCustomer = (EditText) rootView
				.findViewById(R.id.ed_NameCustomer);
		ed_Description = (EditText) rootView.findViewById(R.id.ed_Description);

		imv_trove = (ImageView) rootView.findViewById(R.id.imv_trove);
		imv_hotline = (ImageView) rootView.findViewById(R.id.imv_hotline);
		imv_lamlai = (ImageView) rootView.findViewById(R.id.imv_lamlai);
		imv_guidi = (ImageView) rootView.findViewById(R.id.imv_guidi);

		addEvents();

		return rootView;
	}

	public Bundle getPaymentIndex() {
		return getArguments().getBundle("send");
	}

	private void addEvents() {


		imv_trove.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
					SelectedFragment Selected = new SelectedFragment();
					Selected.setItem(item);
					FragmentTransaction transaction = getFragmentManager()
							.beginTransaction();
					transaction.replace(R.id.details_frag, Selected);
					transaction.addToBackStack(null);
					transaction.commit();

			}
		});
		imv_hotline.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(getActivity(), "0909 990 909", Toast.LENGTH_LONG)
						.show();
			}
		});

		// call date
		cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		dft = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
		strDate = dft.format(cal.getTime());

		// Button xoa het Nhap lai
		imv_lamlai.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				ed_Nametable.setText("");
				ed_NameCustomer.setText("");
				ed_Description.setText("");
			}
		});

		// Button gui Order di
		imv_guidi.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				// TODO Auto-generated method stub
				/*
				 * nhap cac thong tin vao order sau do se goi chuyen len se vo ,
				 * o day thi da xong cong doan cho orderitem
				 */

				String st_NameTable = ed_Nametable.getText().toString();
				String st_NameCustomer = ed_NameCustomer.getText().toString();

				if ( st_NameCustomer.isEmpty() == true) {

					Dialog();

				} else {

					order = new Order();
					for (int j = 0; j < DetailsFragment.ListItem.size(); j++) {
						OrderItem orderitem = new OrderItem();
						orderitem = DetailsFragment.ListItem.get(j);
						order.listItems.add(orderitem);
					}
					for (int i = 0; i < DetailsFragment.ListItem.size(); i++) {
						DetailsFragment.ListItem.remove(i);
					}
					order.setNameOrder(st_NameTable);
					order.setNameCustomer(st_NameCustomer);
					order.setDateOrder(strDate);
					// con cai giam gia phai lam sao ???

					order.setSumPrice(SelectedFragment.tien);
					order.setDescription(ed_Description.getText().toString());

					// getActivity().getContentResolver().insert(OrderMobileProvider.ORDER_CONTENT_URI,
					// OrderMobileProvider.getContentValuesOrder(order));
					// Toast.makeText(getActivity(), " order da duoc nhan",
					// Toast.LENGTH_LONG).show();
					new LoadingsaveOrder().execute("");
					ed_Nametable.setText("");
					ed_NameCustomer.setText("");
					ed_Description.setText("");
				}

			}
		});

	}

	// saveOrder
	class LoadingsaveOrder extends AsyncTask<String, Void, Void> {

		private Exception exception = null;
		ProgressDialog dialog;
		Response respone;

		protected void onPreExecute() {

			dialog = new ProgressDialog(getActivity());
			dialog.setMessage("Loading. Please wait...");
			dialog.setCanceledOnTouchOutside(false);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					LoadingsaveOrder.this.cancel(true);
					dialog.dismiss();
				}

			});
			dialog.show();

		}

		protected Void doInBackground(final String... args) {

			OrderSystemHttpService httpService = new OrderSystemHttpService(
					SERVER_HOST, PORT);
			try {

				httpService.saveOrder(order);

			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				exception = e;
			} catch (HttpApiException e) {
				// TODO Auto-generated catch block
				exception = e;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				exception = e;
			}
			return null;
		}

		protected void onPostExecute(final Void unused) {
			dialog.cancel();

			if (exception == null) {
				if (order.getNameCustomer() != null) {// dieu kien thong bao
					Toast.makeText(getActivity(), "", Toast.LENGTH_LONG).show();
				} else {

				}
			} else {

			}

		}

	}

	@SuppressWarnings("deprecation")
	public void Dialog() {
		AlertDialog alertDialog1 = new AlertDialog.Builder(getActivity())
				.create();
		alertDialog1.setTitle("Cửa Hàng Pizza Hut");
		alertDialog1.setMessage("Vui lòng nhập tên bàn"
				+ "\nVui lòng nhập tên " + "\nVui lòng nhập số điện thoại");
		alertDialog1.setButton("OK", new DialogInterface.OnClickListener() {

			public void onClick(final DialogInterface dialog, final int which) {
				// Write your code here to execute after dialog
			}
		});

		alertDialog1.show();
	}

}
